/* eslint-disable react-hooks/exhaustive-deps */
import { getFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import React, { useCallback, useEffect, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import { io } from 'socket.io-client';
import { Avatar, Divider, List, Skeleton, Grid, Button, Modal, Input, notification } from 'antd';
import Chat from './chat';
import { MenuFoldOutlined, SearchOutlined } from '@ant-design/icons';
import moment from 'moment';

let n = 0;

const { useBreakpoint } = Grid;

const socket = io(REACT_APP_URL, { query: { userId: localStorage.getItem('ID') } });

const typeconfig = {
  text: '文字',
  picture: '图片',
  audio: '语音',
  file: '文件',
};

const Online = () => {
  const [pageIndex, setPageIndex] = useState(1);
  const [name, setName] = useState(null);
  const [data, setData] = useState([]);

  const { loading, ...other } = useRequest(
    async () => {
      let res = await getFetch({
        url: '/wbn-api/wechat/employee/company',
        params: {
          is_chat: 1,
          pageIndex,
          name,
        },
      });
      return res?.data ?? {};
    },
    {
      refreshDeps: [pageIndex, name],
      debounceWait: 400,
      onSuccess: (res) => {
        const thisresult = res?.list ?? [];
        setData((s) => [...s, ...thisresult]);
      },
    },
  );

  const loadMoreData = () => {
    setPageIndex((s) => s + 1);
  };

  const [curitem, setCuritem] = useState(null);
  const [addon, setaddon] = useState();

  useEffect(() => {
    socket.connect();
    socket.off(`chat-customer-${curitem?.customer_id}`);
    socket.off(`chat-user`);
    socket.on(`chat-customer-${curitem?.customer_id}`, (params) => {
      let res = JSON.parse(params);
      if (res?.company_id == curitem?.id) {
      } else {
        notification.info({
          message: '有新的消息',
          description: res?.message_content,
          placement: 'bottomRight',
        });
        setData([]);
        setPageIndex(1);
        other.run();
      }
      setaddon(res);
    });

    socket.on('chat-user', (params) => {
      let res = JSON.parse(params);
      if (res?.company_id == curitem?.id) {
      } else {
        notification.info({
          message: '有新的消息',
          description: res?.message_content,
          placement: 'bottomRight',
        });
        setData([]);
        setPageIndex(1);
        other.run();
      }
      setaddon(res);
    });
  }, [curitem?.customer_id]);

  const { md } = useBreakpoint();

  const [modal, setModal] = useState({
    open: false,
    title: '请选择公司',
    onCancel: () => {
      setModal((s) => ({
        ...s,
        open: false,
      }));
    },
  });

  return (
    <div style={{ display: 'flex', height: '100%', flexDirection: !md ? 'column' : 'row' }}>
      <Modal
        {...modal}
        style={{ top: 12 }}
        footer={false}
        getContainer={() => document.getElementById('root')}
      >
        <div
          style={{
            height: !md ? '680px' : 'calc(100vh - 106px)',
          }}
        >
          <div style={{ height: 50, paddingRight: 16 }}>
            <Input
              prefix={<SearchOutlined />}
              placeholder="输入公司名称、联系人查询"
              value={name}
              onChange={(e) => {
                setData([]);
                setPageIndex(1);
                setName(e.target.value);
              }}
            />
          </div>
          <div
            id={'scrollableDivs'}
            style={{
              height: !md ? '630px' : 'calc(100vh - 156px)',
              overflow: 'auto',
              width: !md ? '100%' : 300,
            }}
          >
            <InfiniteScroll
              dataLength={data?.length}
              next={loadMoreData}
              hasMore={true}
              loader={
                <Skeleton
                  avatar
                  paragraph={{
                    rows: 1,
                  }}
                  active
                />
              }
              endMessage={<Divider plain>暂无更多</Divider>}
              scrollableTarget={'scrollableDivs'}
            >
              <List
                dataSource={data}
                renderItem={(item) => {
                  const lastmsg = item?.last_chat ?? {};
                  const lastmsgtype = lastmsg?.message_type;
                  return (
                    <List.Item
                      key={item.id}
                      style={{
                        backgroundColor: curitem?.id === item?.id ? '#ddd' : '#fff',
                        paddingLeft: 12,
                      }}
                      onClick={() => {
                        setCuritem(item);
                        setModal((s) => ({
                          ...s,
                          open: false,
                        }));
                      }}
                    >
                      <List.Item.Meta
                        avatar={<Avatar>{item.name.charAt(0)}</Avatar>}
                        title={<a>{item.name}</a>}
                        description={
                          <div>
                            <span>
                              {item.customer_name}
                              <Divider type="vertical" />
                              <b>{item.customer_phone}</b>
                            </span>
                            <br />
                            <div className="spread" style={{ alignItems: 'baseline', gap: 4 }}>
                              <div
                                className="centerl"
                                style={{ gap: 2, flex: 1, overflow: 'hidden' }}
                              >
                                {item.unread_num > 0 ? (
                                  <div
                                    style={{
                                      width: 20,
                                      height: 20,
                                      borderRadius: 50,
                                      backgroundColor: 'red',
                                      color: '#fff',
                                      flexShrink: 0,
                                      fontSize: 10,
                                    }}
                                    className="center"
                                  >
                                    {item.unread_num > 9 ? '9+' : item.unread_num}
                                  </div>
                                ) : null}
                                <span
                                  className="oneline"
                                  style={{ color: item.unread_num > 0 ? 'red' : '#000', flex: 1 }}
                                >
                                  {lastmsgtype === 'text'
                                    ? lastmsg?.message_content
                                    : lastmsgtype
                                    ? `[ ${typeconfig[lastmsgtype]} ]`
                                    : ''}
                                </span>
                              </div>

                              <div style={{ flexShrink: 0, paddingRight: 6, fontSize: 12 }}>
                                {moment(item.last_chat_time).format('YYYY-MM-DD HH:mm:ss')}
                              </div>
                            </div>
                          </div>
                        }
                      />
                    </List.Item>
                  );
                }}
              />
            </InfiniteScroll>
          </div>
        </div>
      </Modal>
      {!md ? (
        <div className="spread" style={{ marginBottom: 6 }}>
          <b>{curitem?.customer_name ?? '请选择'}</b>
          <Button
            type="primary"
            icon={<MenuFoldOutlined />}
            onClick={() => {
              setModal((s) => ({
                ...s,
                open: true,
              }));
            }}
          />
        </div>
      ) : (
        <div
          style={{
            height: !md ? '680px' : 'calc(100vh - 106px)',
          }}
        >
          <div style={{ height: 50, paddingRight: 16 }}>
            <Input
              prefix={<SearchOutlined />}
              placeholder="输入公司名称、联系人查询"
              value={name}
              onChange={(e) => {
                setData([]);
                setPageIndex(1);
                setName(e.target.value);
              }}
            />
          </div>
          <div
            id={'scrollableDiv'}
            style={{
              height: !md ? '630px' : 'calc(100vh - 156px)',
              overflow: 'auto',
              width: !md ? '100%' : 300,
            }}
          >
            <InfiniteScroll
              dataLength={data?.length}
              next={loadMoreData}
              hasMore={true}
              loader={
                <Skeleton
                  avatar
                  paragraph={{
                    rows: 1,
                  }}
                  active
                />
              }
              endMessage={<Divider plain>暂无更多</Divider>}
              scrollableTarget={'scrollableDiv'}
            >
              <List
                dataSource={data}
                renderItem={(item) => {
                  const lastmsg = item?.last_chat ?? {};
                  const lastmsgtype = lastmsg?.message_type;
                  return (
                    <List.Item
                      key={item.id}
                      style={{
                        backgroundColor: curitem?.id === item?.id ? '#ddd' : '#fff',
                        paddingLeft: 12,
                      }}
                      onClick={() => {
                        setCuritem(item);
                        setModal((s) => ({
                          ...s,
                          open: false,
                        }));
                      }}
                    >
                      <List.Item.Meta
                        avatar={<Avatar>{item.name.charAt(0)}</Avatar>}
                        title={<a>{item.name}</a>}
                        description={
                          <div>
                            <span>
                              {item.customer_name}
                              <Divider type="vertical" />
                              <b>{item.customer_phone}</b>
                            </span>
                            <br />
                            <div className="spread" style={{ alignItems: 'baseline', gap: 4 }}>
                              <div
                                className="centerl"
                                style={{ gap: 2, flex: 1, overflow: 'hidden' }}
                              >
                                {item.unread_num > 0 ? (
                                  <div
                                    style={{
                                      width: 20,
                                      height: 20,
                                      borderRadius: 50,
                                      backgroundColor: 'red',
                                      color: '#fff',
                                      flexShrink: 0,
                                      fontSize: 10,
                                    }}
                                    className="center"
                                  >
                                    {item.unread_num > 9 ? '9+' : item.unread_num}
                                  </div>
                                ) : null}
                                <span
                                  className="oneline"
                                  style={{ color: item.unread_num > 0 ? 'red' : '#000', flex: 1 }}
                                >
                                  {lastmsgtype === 'text'
                                    ? lastmsg?.message_content
                                    : lastmsgtype
                                    ? `[ ${typeconfig[lastmsgtype]} ]`
                                    : ''}
                                </span>
                              </div>

                              <div style={{ flexShrink: 0, paddingRight: 6, fontSize: 12 }}>
                                {moment(item.last_chat_time).format('YYYY-MM-DD HH:mm:ss')}
                              </div>
                            </div>
                          </div>
                        }
                      />
                    </List.Item>
                  );
                }}
              />
            </InfiniteScroll>
          </div>
        </div>
      )}

      <div style={{ flex: 1, backgroundColor: 'white', height: '100%' }}>
        <Chat curitem={curitem} socket={socket} addon={addon} />
      </div>
    </div>
  );
};
export default Online;
